package com.lyh.utils;

import com.lyh.pojo.PersonAndUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class EmailUtils {

    @Autowired //发送邮件的对象
    private JavaMailSenderImpl mailSender;
    @Autowired
    private JedisPoolUtils jedis;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Async
    public void sendMail(PersonAndUser user){
        //数据保存成功, 生成邮箱激活码
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            String username = user.getUsername();
            String active = UUIDUtils.getUUID();
            //创建激活码并存放到redis中
            jedis.setLimitTimeValue(username, active,60*60*48);//有48小时的有效时间

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setSubject("12354山卡拉火车网--激活邮件");
            helper.setText(HtmlCode.getHtml(username,active),true);//true可以解析html代码
            helper.setTo(user.getEmail());//获取用户的注册邮箱
            helper.setFrom("2597247763@qq.com");
            mailSender.send(mimeMessage);//发送邮件
            System.out.println("异步任务: 发送邮件 已完成");
        } catch (MessagingException e) {
            logger.error("创建复杂邮件对象发生错误!");
            e.printStackTrace();
        }
    }
}
